package info.batcloud.fanli.core.item.collection;

import com.ctospace.archit.common.pagination.Paging;
import com.jd.open.api.sdk.JdException;
import info.batcloud.fanli.core.dto.CommissionItemFetchDTO;
import info.batcloud.fanli.core.constants.JosConstatns;
import info.batcloud.fanli.core.enums.CommissionItemStatus;
import info.batcloud.fanli.core.enums.EcomPlat;
import info.batcloud.fanli.core.enums.ItemSelectionType;
import info.batcloud.fanli.core.helper.JdHelper;
import info.batcloud.fanli.core.jos.JosApp;
import info.batcloud.fanli.core.service.JdUnionApiService;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.laxiaoke.open.domain.jd.union.CouponGoods;
import info.batcloud.laxiaoke.open.domain.jd.union.CouponGoodsResult;
import info.batcloud.laxiaoke.open.request.jd.union.QueryCouponGoodsRequest;
import info.batcloud.laxiaoke.open.response.jd.union.QueryCouponGoodsResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.*;
import java.util.function.Consumer;

@Component
public class JdQueryCouponGoodsSelectionCollector extends AbstractItemSelectionCollector<JdQueryCouponGoodsSelectionCollector.JdQueryCouponGoodsContext> {

    private static final Logger logger = LoggerFactory.getLogger(JdQueryCouponGoodsSelectionCollector.class);

    @Inject
    @Qualifier(JosConstatns.UNION_APP)
    private JosApp unionApp;

    @Inject
    private SystemSettingService systemSettingService;

    @Inject
    private JdUnionApiService jdUnionApiService;

    @Override
    public CollectResult collect(JdQueryCouponGoodsSelectionCollector.JdQueryCouponGoodsContext context,
                                 Consumer<Paging<CommissionItemFetchDTO>> pagingConsumer) {
        CollectResult result = new CollectResult();
        QueryCouponGoodsRequest request = new QueryCouponGoodsRequest();
        request.setPageSize(context.getPageSize());
        if (context.getCid3() != null) {
            request.setCid3(context.getCid3());
        }
        if(StringUtils.isNotBlank(context.getSkuIds())) {
            request.setSkuIdList(context.getSkuIds());
        }
        if (StringUtils.isNotBlank(context.getGoodsKeyword())) {
            request.setGoodsKeyword(context.getGoodsKeyword());
        }
        if (context.getPriceFrom() != null) {
            request.setPriceFrom(Double.valueOf(context.getPriceFrom()));
        }
        if (context.getPriceTo() != null) {
            request.setPriceTo(Double.valueOf(context.getPriceTo()));
        }
        try {
            int page = context.getStartPage();
            int num = 0;
            request.setPageSize(30);
            while (true) {
                logger.info("同步" + page + "页");
                request.setPageIndex(page);
                QueryCouponGoodsResponse res = jdUnionApiService.queryCouponGoodsResult(request);
                CouponGoodsResult goodsResult = res.getData();
                int total = goodsResult.getTotal();
                List<CouponGoods> list = goodsResult.getData();
                if (list == null) {
                    break;
                }
                List<CommissionItemFetchDTO> ciList = new ArrayList<>();
                for (CouponGoods couponGoods : goodsResult.getData()) {
                    ciList.add(toCommissionItem(context, couponGoods));
                }
                Paging<CommissionItemFetchDTO> paging = new Paging<>();
                paging.setResults(ciList);
                paging.setPage(page);
                paging.setPageSize(context.getPageSize());
                paging.setTotal(goodsResult.getTotal());
                pagingConsumer.accept(paging);
                num += list.size();
                if (total <= num) {
                    break;
                }
                if (list.size() < 30) {
                    break;
                }
                if (page >= context.getMaxPage()) {
                    break;
                }
                page++;
            }
            logger.info("同步完成");
            result.setSuccess(true);
            result.setTotalNum(num);
        } catch (JdException e) {
            logger.error("同步失败", e);
            result.setSuccess(false);
            result.setErrMsg(e.getLocalizedMessage());
        }
        return result;
    }

    private static CommissionItemFetchDTO toCommissionItem(JdQueryCouponGoodsSelectionCollector.JdQueryCouponGoodsContext context, CouponGoods couponGoods) {
        CommissionItemFetchDTO dto = new CommissionItemFetchDTO();
        Date now = new Date();
        dto.setListTime(now);
        /**
         * 商品的下架时间为当前的日期+7天，优惠券的下架时间，活动的下架时间取最大者
         * */
        Date delistTime = DateUtils.addDays(now, 7);

        CouponGoods.Coupon coupon;
        if (couponGoods.getCouponList() == null
                || couponGoods.getCouponList().size() == 0) {
            coupon = new CouponGoods.Coupon();
            coupon.setBeginTime(System.currentTimeMillis());
            coupon.setDiscount(0);
            coupon.setEndTime(DateUtils.addDays(now, 7).getTime());
            dto.setCoupon(false);
        } else {
            Collections.sort(couponGoods.getCouponList(), (o1, o2) -> Float.valueOf(o2.getDiscount() - o1.getDiscount()).intValue());
            coupon = couponGoods.getCouponList().get(0);
            dto.setCoupon(true);
        }
        Date couponEndTime = new Date(coupon.getEndTime());
        dto.setDelistTime(Collections.max(Arrays.asList(delistTime, couponEndTime)));
        dto.setCouponStartTime(new Date(coupon.getBeginTime()));
        List<Long> sourceCatIdList = new ArrayList<>();
        sourceCatIdList.add(Long.valueOf(couponGoods.getCid()));
        sourceCatIdList.add(Long.valueOf(couponGoods.getCid2()));
        sourceCatIdList.add(Long.valueOf(couponGoods.getCid3()));
        dto.setSourceCatIdList(sourceCatIdList);
        dto.setShopTitle(couponGoods.getIsJdSale() == 1 ? "京东自营" : "京东");
        dto.setCouponRemainCount(100);
        dto.setCouponTotalCount(100);

        dto.setCouponValue(coupon.getDiscount());
        dto.setSourceItemUrl(JdHelper.completeUrl(couponGoods.getMateriaUrl()));
        dto.setSourceItemId(Long.valueOf(couponGoods.getSkuId()));
        dto.setTitle(couponGoods.getSkuName());
        dto.setSourceItemClickUrl(couponGoods.getMateriaUrl());
        dto.setCouponClickUrl(JdHelper.completeUrl(coupon.getLink()));
        dto.setOriginPrice(couponGoods.getWlPrice());
        float couponStartFee = coupon.getQuota();
        dto.setCouponThresholdAmount(couponStartFee);
        dto.setCommissionRate(couponGoods.getWlCommissionShare());
        dto.setEcomPlat(EcomPlat.JD);
        dto.setSeckill(couponGoods.getIsSeckill() == 1 ? true : false);
        dto.setImgList(new ArrayList<>());
        dto.setPicUrl(JdHelper.imageUrl(couponGoods.getImageUrl()));
        dto.setSales(Long.valueOf(couponGoods.getInOrderCount()).intValue());
        dto.setStatus(CommissionItemStatus.ONSALE);
        dto.setChannelId(context.getChannelId());
        dto.setShopcatId(context.getShopcatId());
        dto.setRecommend(context.isRecommend());
        return dto;
    }

    @Override
    public Class<JdQueryCouponGoodsContext> getContextType() {
        return JdQueryCouponGoodsContext.class;
    }

    @Override
    protected ItemSelectionType getItemSelectionType() {
        return ItemSelectionType.JD_QUERY_COUPON_GOODS;
    }

    public static class JdQueryCouponGoodsContext extends Context {

        private String skuIds;
        private Long cid3;
        private String goodsKeyword;

        private Float priceFrom;
        private Float priceTo;

        public String getSkuIds() {
            return skuIds;
        }

        public void setSkuIds(String skuIds) {
            this.skuIds = skuIds;
        }

        public Long getCid3() {
            return cid3;
        }

        public void setCid3(Long cid3) {
            this.cid3 = cid3;
        }

        public String getGoodsKeyword() {
            return goodsKeyword;
        }

        public void setGoodsKeyword(String goodsKeyword) {
            this.goodsKeyword = goodsKeyword;
        }

        public Float getPriceFrom() {
            return priceFrom;
        }

        public void setPriceFrom(Float priceFrom) {
            this.priceFrom = priceFrom;
        }

        public Float getPriceTo() {
            return priceTo;
        }

        public void setPriceTo(Float priceTo) {
            this.priceTo = priceTo;
        }
    }
}
